import { editProfile,logout,setupUserProfile} from "./auth.js";
window.editProfile = editProfile;
window.logout = logout;
window.setupUserProfile = setupUserProfile;
document.addEventListener('DOMContentLoaded', async () => {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username') || 'defaultUser';
    await setupUserProfile(username);
    const weekSelector = document.getElementById('weekSelector');
    const currentTimeDisplay = document.querySelector('.toolbar .current-time');
    const semesterInfo = document.querySelector('.semester-info');

    // 初始化周次选择器
    const initWeekSelector = () => {
        // 生成1 - 16周的选项
        for (let week = 1; week <= 16; week++) {
            const option = document.createElement('option');
            option.value = week;
            option.textContent = `第${week}周`;
            weekSelector.appendChild(option);
        }

        // 默认选择当前周次，确保在1 - 16周范围内
        const currentWeek = Math.min(16, Math.max(1, new Date().getWeekNumber()));
        weekSelector.value = currentWeek;
        semesterInfo.textContent = `2024 - 2025 春季学期 第${currentWeek}周`;
    };

    // 实时时间更新
    const updateCurrentTime = () => {
        const now = new Date();
        currentTimeDisplay.textContent = now.toLocaleTimeString();
    };
    setInterval(updateCurrentTime, 1000);

    // 颜色生成器（改进版）
    const colorGenerator = (() => {
        const cache = {};
        return (courseName) => {
            if (!cache[courseName]) {
                let hash = 0;
                for (let i = 0; i < courseName.length; i++) {
                    hash = courseName.charCodeAt(i) + ((hash << 5) - hash);
                }
                const hue = hash % 360;
                cache[courseName] = `hsl(${hue}, 75%, 65%)`;
            }
            return cache[courseName];
        };
    })();

    // 课程渲染引擎
    const renderSchedule = async (selectedWeek) => {
        try {
            // 更新标题显示当前周次
            semesterInfo.textContent = `2024 - 2025 春季学期 第${selectedWeek}周`;

            const response = await fetch(`/get-selected-courses?username=${username}`);
            if (!response.ok) {
                throw new Error('获取课程数据失败');
            }
            const courses = await response.json();
            const tableBody = document.querySelector('#courseScheduleTable tbody');

            // 清空现有内容
            tableBody.innerHTML = '';

            // 记录每列剩余的跨行数
            const rowspanLeft = new Array(7).fill(0);

            // 生成时间行（1 - 14节）
            for (let period = 1; period <= 14; period++) {
                const row = document.createElement('tr');

                // 时间列
                const timeCell = document.createElement('td');
                timeCell.className = 'time-column';
                timeCell.textContent = period;
                row.appendChild(timeCell);

                // 每天的课程单元格
                for (let day = 1; day <= 7; day++) {
                    if (rowspanLeft[day - 1] > 0) {
                        // 如果该列还有跨行，跳过该单元格
                        rowspanLeft[day - 1]--;
                        continue;
                    }

                    const cell = document.createElement('td');
                    cell.className = 'course-cell';

                    // 查找当前单元格的课程
                    const currentCourses = courses.filter(course => {
                        const [courseDay, coursePeriod] = course.course_time.split('_');
                        const [start, end] = coursePeriod.split('-').map(Number);
                        return courseDay == day && period >= start && period <= end;
                    });

                    // 渲染课程块
                    currentCourses.forEach(course => {
                        const teachWeeks = course.teach_weeks.split(',').flatMap(range => {
                            if (range.includes('-')) {
                                const [start, end] = range.split('-').map(Number);
                                return Array.from({ length: end - start + 1 }, (_, i) => start + i);
                            }
                            return [Number(range)];
                        });

                        const isInWeek = teachWeeks.includes(Number(selectedWeek));

                        if (isInWeek) {
                            const container = document.createElement('div');
                            container.className = 'course-container';

                            // 计算跨行数
                            const [startPeriod, endPeriod] = course.course_time.split('_')[1]
                                .split('-').map(Number);
                            const rowSpan = endPeriod - startPeriod + 1;

                            if (period === startPeriod) {
                                cell.rowSpan = rowSpan;
                                rowspanLeft[day - 1] = rowSpan - 1;

                                const block = document.createElement('div');
                                block.className = 'course-block';
                                block.style.backgroundColor = colorGenerator(course.course_name);

                                // 课程信息处理
                                let displayName = course.course_name;

                                block.innerHTML = `
                                    <div class="course-info" title="${escapeHTML(course.course_name)}">
                                        <div class="course-name">${escapeHTML(displayName)}</div>
                                        ${course.place ? `<div class="course-location">${escapeHTML(course.place)}</div>` : ''}
                                    </div>
                                `;

                                // 添加点击事件
                                block.addEventListener('click', () => {
                                    openCourseInfoModal(course);
                                });

                                container.appendChild(block);
                            }

                            cell.appendChild(container);
                        }
                    });

                    row.appendChild(cell);
                }

                tableBody.appendChild(row);
            }
        } catch (error) {
            console.error('渲染课表时出错:', error);
            alert('渲染课表时出错，请稍后重试');
        }
    };

    // 事件监听
    weekSelector.addEventListener('change', (e) => {
        renderSchedule(e.target.value);
    });

    // 初始化
    initWeekSelector();
    renderSchedule(weekSelector.value);
});

// 扩展Date对象获取周次
Date.prototype.getWeekNumber = function() {
    const start = new Date(this.getFullYear(), 0, 1);
    const dayOfYear = (this - start) / 86400000;
    return Math.ceil((dayOfYear + start.getDay() + 1) / 7);
};

function goBack() {
    window.history.back();
}

// 打开课程信息模态框
async function openCourseInfoModal(course) {
    const { course_name, teacher_user_id, place, teach_weeks, course_code, credits, study_period, assessment_method, course_time } = course;

    // 解析上课节次
    const [day, periodRange] = course_time.split('_');
    const [startPeriod, endPeriod] = periodRange.split('-');
    const classPeriod = Array.from({ length: endPeriod - startPeriod + 1 }, (_, i) => String(Number(startPeriod) + i).padStart(2, '0')).join('');

    // 转换时间
    const startIndex = Number(startPeriod) - 1;
    const endIndex = Number(endPeriod) - 1;
    const startTimes = ['8:00', '8:50', '9:50', '10:40', '11:30', '14:00', '14:50', '15:50', '16:40', '17:30', '19:00', '19:50', '20:40', '21:30'];
    const startTime = startTimes[startIndex];
    const endTimeParts = startTimes[endIndex].split(':');
    const endTime = new Date(0, 0, 0, Number(endTimeParts[0]), Number(endTimeParts[1]) + 45);
    const formattedEndTime = `${endTime.getHours().toString().padStart(2, '0')}:${endTime.getMinutes().toString().padStart(2, '0')}`;
    const time = `${startTime}-${formattedEndTime}`;

    // 获取教师姓名
    let teacherName = '';
    try {
        const response = await fetch(`/get-teacher-name/${teacher_user_id}`);
        const data = await response.json();
        teacherName = data.teacherName;
    } catch (error) {
        console.error('Error getting teacher name:', error);
    }

    // 填充模态框内容
    document.getElementById('courseInfoModalTitle').textContent = escapeHTML(course_name);
    document.getElementById('courseTeacher').textContent = escapeHTML(teacherName);
    document.getElementById('courseTime').textContent = time;
    document.getElementById('coursePlace').textContent = place;
    document.getElementById('courseTeachWeeks').textContent = teach_weeks;
    document.getElementById('courseCode').textContent = course_code;
    document.getElementById('courseCredits').textContent = credits;
    document.getElementById('courseStudyPeriod').textContent = study_period;
    document.getElementById('courseAssessmentMethod').textContent = assessment_method;
    document.getElementById('courseClassPeriod').textContent = classPeriod;

    // 显示模态框
    document.getElementById('courseInfoModal').style.display = 'block';
}

// 关闭课程信息模态框
function closeCourseInfoModal() {
    document.getElementById('courseInfoModal').style.display = 'none';
}

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href ='success.html'+window.location.search;
        });
    }
});

window.openCourseInfoModal = openCourseInfoModal;
window.closeCourseInfoModal = closeCourseInfoModal;

function escapeHTML(str) {
    if (typeof str !== 'string') return str;
    if (!str) return '';
    return str
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

export{
     openCourseInfoModal,
     closeCourseInfoModal,
     goBack,
     escapeHTML,
}